<template>
  <div class="typewriter">
    <span>{{ displayedText }}</span>
    <span class="cursor" v-show="isTyping">
      <svg class="loading-spinner" viewBox="0 0 50 50">
        <circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="4"></circle>
      </svg>
    </span>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  text: {
    type: String,
    required: true
  },
  speed: {
    type: Number,
    default: 50
  },
  delay: {
    type: Number,
    default: 100
  }
});

const displayedText = ref('');
const isTyping = ref(true);
let typingInterval;

const startTyping = () => {
  isTyping.value = true;
  displayedText.value = '';
  clearInterval(typingInterval);

  if (props.text) {
    setTimeout(() => {
      let i = 0;
      typingInterval = setInterval(() => {
        if (i < props.text.length) {
          isTyping.value = false;
          displayedText.value += props.text.charAt(i);
          i++;
        } else {
          clearInterval(typingInterval);
        }
      }, props.speed);
    }, props.delay);
  }
};

watch(
  () => props.text,
  () => {
    startTyping();
  },
  { immediate: true }
);

onUnmounted(() => {
  clearInterval(typingInterval);
});
</script>

<style scoped>
.typewriter {
  display: inline-block;
}

.cursor {
  display: inline-flex;
  align-items: center;
  margin-left: 2px;
}

.loading-spinner {
  width: 1em;
  height: 1em;
  animation: rotate 2s linear infinite;
}

.path {
  stroke: currentColor;
  stroke-linecap: round;
  animation: dash 1.5s ease-in-out infinite;
}

@keyframes rotate {
  100% {
    transform: rotate(360deg);
  }
}

@keyframes dash {
  0% {
    stroke-dasharray: 1, 150;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -35;
  }
  100% {
    stroke-dasharray: 90, 150;
    stroke-dashoffset: -124;
  }
}
</style>